package com.atguigu.srb.core.controller.api;

import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.LendItem;
import com.atguigu.srb.core.pojo.vo.InvestVO;
import com.atguigu.srb.core.result.R;
import com.atguigu.srb.core.service.LendItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author AtLong
 * @since 2022-06-11
 */
@RestController
@RequestMapping("/api/core/lendItem")
@Api(tags = "标的出借记录表")
@Slf4j
public class WebLendItemController {

    @Autowired
    LendItemService lendItemService;

    @ApiOperation(value = "标的进行投资")
    @PostMapping("/auth/commitInvest")
    public R commitInvest(HttpServletRequest request, @RequestBody InvestVO investVO) {  // lendId = 1, investAmount=500
        // 从head中获取Token,并对token进行校验,确保用户已经登录,并从token中获取userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);  // userId = 10
        String userName = JwtUtils.getUserName(token);
        investVO.setInvestUserId(userId);
        investVO.setInvestName(userName);
        // 调用业务层投资接口
        String formStr = lendItemService.commitInvest(investVO);

        return R.ok().data("formStr",formStr);
       // return R.ok().data("formStr",formStr);
    }

    @ApiOperation(value = "标的投资异步回调接口")
    @PostMapping("/notify")
    public String asyncNotify(HttpServletRequest request) {
        // 获取汇付宝先srb发起回调的请求参数
        Map<String, String[]> requestParameterMap = request.getParameterMap();
        Map<String, Object> paramMap = RequestHelper.switchMap(requestParameterMap);
        log.info("账户充值的回调接收参数如下:" + JSON.toJSONString(paramMap));
        // 校验签名 ,校验状态码
        if (!RequestHelper.isSignEquals(paramMap) || !"0001".equals(paramMap.get("resultCode"))) {
            return "fail";
        }
       String success = lendItemService.asyncNotifyLendItem(paramMap);

        return "success";
    }


}
